#include "os.h"
#include <stdlib.h>
#include <string.h>
#include "smtp.h"
#include "cJSON.h"


#define CHAR_MIN 'a'
#define CHAR_MAX 'z' 	//输出随机字符串每个字符的最大最小值。
void random_string(int random_len, char* random_buf, unsigned long seed)
{
	random_buf[random_len + 1] = '\0';
    //srand(time(NULL));
    srand(seed);
    for(int i = 0; i < random_len; i ++){
        random_buf[i] = rand()%(CHAR_MAX-CHAR_MIN + 1) + CHAR_MIN;
    }
}


/**
  * @brief  Get file-stream's length.
  * @Notes  None.
  * @param  fp, file pointer.
  * @retval stream's length which in a file.
  */
long fstr_len(FILE* fp)
{
	long stream_len; 
	fseek(fp, 0, SEEK_END); 
	stream_len = ftell(fp); 
	fseek(fp, 0, SEEK_SET);
	//printf("length=%d\n", stream_len);
	return stream_len;
}

/**
  * @brief  Allocate memory space for file-stream.
  * @Notes  None.
  * @param  fp, file pointer.
  * @param  stream, memory buffer for stream.
  * @retval stream's length which in a file.
  */
long fstr_alloc(FILE* fp, char** stream)
{
	long chars = fstr_len(fp);
	long rdsz;
	if(chars == 0)
	{
		return 0;
	}
	else{
		*stream = (char*)malloc((chars)*sizeof(char));
		rdsz = fread(*stream, 1, chars, fp);
		//printf("fstrbuf:%s\n", fstrbuf);
		return rdsz;
	}
}

/**
  * @brief  Release memory space of file-stream.
  * @Notes  None.
  * @param  fstrbuf, memory buffer for stream.
  * @retval None.
  */
void fstr_free(char* fstrbuf)
{
	if(fstrbuf != NULL)
		free(fstrbuf);
}


struct __smtp_conf CfgSmtp;

int load_conf_smtp(char* cfgfile)
{
	FILE* fp = NULL; 
	char* stream; long txtlen = 0;
	cJSON *json;
	if((fp=fopen(cfgfile, "r")) == NULL)	//尝试读文件
	{
		fprintf(stderr, "cJSON/> {ERROR} Config file '%s' load faild\n", cfgfile);
		return 1;
	}
	else
	{
		txtlen = fstr_alloc(fp, &stream);
		//printf("%s\n", stream);
		json = cJSON_Parse(stream);
		cJSON* smtp = cJSON_GetObjectItem(json, "smtp");
		strcpy(CfgSmtp.SmtpServer, 		cJSON_GetObjectItem(smtp, "SmtpServer")->valuestring);
		strcpy(CfgSmtp.SmtpPort, 		cJSON_GetObjectItem(smtp, "SmtpPort")->valuestring);
		strcpy(CfgSmtp.SmtpCaFile, 		cJSON_GetObjectItem(smtp, "SmtpCaFile")->valuestring);
		strcpy(CfgSmtp.SmtpUser, 		cJSON_GetObjectItem(smtp, "SmtpUser")->valuestring);
		strcpy(CfgSmtp.SmtpUserPass, 	cJSON_GetObjectItem(smtp, "SmtpUserPass")->valuestring);
		strcpy(CfgSmtp.Sender, 			cJSON_GetObjectItem(smtp, "Sender")->valuestring);
		strcpy(CfgSmtp.SenderAlias, 	cJSON_GetObjectItem(smtp, "SenderAlias")->valuestring);
		strcpy(CfgSmtp.Subject, 		cJSON_GetObjectItem(smtp, "Subject")->valuestring);
		strcpy(CfgSmtp.Receiver, 		cJSON_GetObjectItem(smtp, "Receiver")->valuestring);
		strcpy(CfgSmtp.ReceiverAlias, 	cJSON_GetObjectItem(smtp, "ReceiverAlias")->valuestring);

		cJSON_Delete(json);
		fstr_free(stream);
		fclose(fp); fp=NULL;
		fprintf(stderr, "cJSON/> {INFO} Config file '%s' load success.\n", cfgfile);
	}

	return 0;	
}

void print_conf_smtp(void)
{
	printf("SmtpServer: %s\n", CfgSmtp.SmtpServer);
	printf("SmtpPort: %s\n", CfgSmtp.SmtpPort);
	printf("SmtpCaFile: %s\n", CfgSmtp.SmtpCaFile);
	printf("SmtpUser: %s\n", CfgSmtp.SmtpUser);
	printf("SmtpUserPass: %s\n", CfgSmtp.SmtpUserPass);
	printf("Sender: %s\n", CfgSmtp.Sender);
	printf("SenderAlias: %s\n", CfgSmtp.SenderAlias);
	printf("Subject: %s\n", CfgSmtp.Subject);
	printf("Receiver: %s\n", CfgSmtp.Receiver);
	printf("ReceiverAlias: %s\n", CfgSmtp.ReceiverAlias);
}

int sendmail(struct __smtp_conf* Mail, char* MailContent)
{
  struct smtp *smtp;
  enum smtp_status_code rc;

  smtp_open(Mail->SmtpServer,
            Mail->SmtpPort,
            //Mail->SmtpConnSecurity,
            SMTP_SECURITY_NONE,
            //Mail->SmtpLog,
            SMTP_DEBUG,
            //Mail->SmtpCaFile,
            (strncmp(Mail->SmtpCaFile, "NULL", 4)==0)?NULL:(Mail->SmtpCaFile),
            &smtp);
  smtp_auth(smtp,
            //Mail->SmtpAuth,
  			SMTP_AUTH_NONE,
            Mail->SmtpUser,
            Mail->SmtpUserPass);
  smtp_address_add(smtp,
                   SMTP_ADDRESS_FROM,
                   Mail->Sender,
                   Mail->SenderAlias);
  smtp_address_add(smtp,
                   SMTP_ADDRESS_TO,
                   Mail->Receiver,
                   Mail->ReceiverAlias);
  smtp_header_add(smtp,
                  "Subject",
                  Mail->Subject);
  
  //smtp_header_add(smtp, "Content-Type", "text/html");

  smtp_mail(smtp, MailContent);
  rc = smtp_close(smtp);
  if(rc != SMTP_STATUS_OK){
    fprintf(stderr, "smtp failed: %s\n", smtp_status_code_errstr(rc));
    return 1;
  }
  return 0;
}